package com.jiangjiang.eshop.pay.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangjiang.eshop.pay.convert.PayTransactionConvert;
import com.jiangjiang.eshop.pay.dao.PayTransactionMapper;
import com.jiangjiang.eshop.pay.dto.PayTransactionDTO;
import com.jiangjiang.eshop.pay.dto.PayTransactionEntity;
import com.jiangjiang.eshop.pay.dto.PayTransactionQuery;
import com.jiangjiang.eshop.pay.dto.PayTransactionQueryCondition;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Jianghaowen
 * @Date 2021/9/30
 * @Description: TODO
 * @Version V1.0
 **/
@Service
public class PayTransactionService extends ServiceImpl<PayTransactionMapper, PayTransactionEntity> {

    @Autowired
    private PayTransactionConvert payTransactionConvert;

    /**
     * 交易流水保存
     * @param payTransactionDTO
     */
    public void save(PayTransactionDTO payTransactionDTO) {
        this.save(payTransactionConvert.convertDTO2Entity(payTransactionDTO));
    }

    /**
     * 根据查询条件查询支付流水
     * @param condition 查询条件
     * @return 支付流水
     */
    public List<PayTransactionDTO> queryByCondition(PayTransactionQueryCondition condition) {
        LambdaQueryWrapper<PayTransactionEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(condition.getTransactionChannel() != null, PayTransactionEntity::getTransactionChannel, condition.getTransactionChannel())
                .eq(condition.getStatus() != null, PayTransactionEntity::getStatus, condition.getStatus())
                .eq(Strings.isNotEmpty(condition.getOrderNo()), PayTransactionEntity::getOrderNo, condition.getOrderNo())
        ;

        return payTransactionConvert.convertEntities2DTOList(this.list(wrapper));
    }

    /**
     * 交易流水更新
     * @param payTransactionDTO
     */
    public void update(PayTransactionDTO payTransactionDTO) {
        PayTransactionEntity payTransaction = payTransactionConvert.convertDTO2Entity(payTransactionDTO);
        this.updateById(payTransaction);
    }

    /**
     * 交易流水分页查询
     * @param query 查询条件
     * @return 查询结果
     */
    public Page<PayTransactionDTO> queryForPage(PayTransactionQuery query) {
        Page<PayTransactionEntity> page = new Page<>(query.getPageSize(), query.getPageNo(), true);
        return payTransactionConvert.convertPage2DTO(this.getBaseMapper().selectPage(page, null));
    }
}
